<?php

/**
 * BackupManager управляет бекапами.
 *
 * @package Admin
 * @author  lucky
 */
class BackupManager
{

	/**
	 * root_dir путь к дириктории, где храняться архивы.
	 *
	 * @var mixed
	 * @access public
	 */
	var $root_dir = NULL;
	/**
	 * naming политика именования архивов.
	 *
	 * @var mixed
	 * @access public
	 */
	var $naming = NULL;

	public function __construct ($cfg)
	{
		$this->naming = new BackupNaming($this);
		foreach ($cfg as $k=>$v) $this->$k = $v;

		// если нет директории, то постараемся её создать
		if (!is_dir($this->root_dir)) {
			mkdir (rtrim($this->root_dir, '/'), 0700, true);
		}
	} // end of __construct
	public function createBackup ()
	{
		$backup = $this->buildBackupFromFile($this->naming->makeName(), true);
		return $backup;
	} // end of method createBackup
	public function deleteBackup ($backup)
	{
		unlink($this->root_dir . $backup->filename);
		$backup->is_dead = true;
		return true;
	} // end of method deleteBackup
	public function listBackups ()
	{
		$dir = dir($this->root_dir);
		$backups = array();
		while (false !== ($entry = $dir->read())) {
			if (is_file($this->root_dir.$entry)) {
				$backups[$entry] = $this->buildBackupFromFile($entry);
			}
		}
		$dir->close();
		usort($backups, array($this, 'compareCTime'));
		return $backups;
	} // end of method listBackups

	public function findBackupByFilename ($filename)
	{
		return $this->buildBackupFromFile($filename);
	} // end of method findBackupByFilename

	public function buildBackupFromFile ($filename, $can_create=false)
	{
		$backup = new Backup($this);
		$backup->filename = $filename;
		if (!is_file($backup->getPath()) && !$can_create) $backup = NULL;
		return $backup;
	} // end of method buildBackupFromFile

	public function compareCTime ($a, $b)
	{
		return $a->getCTime() < $b->getCTime();
	} // end of method sort
}

/**
 * BackupNaming политика именования бекапов.
 *
 * @package Admin
 * @author  lucky
 */
class BackupNaming
{
	public function __construct ($backup_manager)
	{
		$this->bm = $backup_manager;
	} // end of __construct
	/**
	 * makeName создать имя архива.
	 *
	 * Возможно уникальное, но все зависит от логики конкретной политики.
	 *
	 * @return string
	 */
	public function makeName ()
	{
		return 'db_'.date('Y-m-d-H-i-s').'.sql';
	} // end of method makeName
}

class Backup
{
	var $filename = NULL;

	public function __construct ($backup_manager)
	{
		$this->bm = $backup_manager;
	} // end of __construct
	public function getPath ()
	{
		$path = $this->bm->root_dir . $this->filename;
		return $path;
	} // end of method getPath
	public function getCTime ()
	{
		return filemtime($this->getPath());
	} // end of method getCTime
	public function getSize ()
	{
		return filesize($this->getPath());
	} // end of method getCTime
}

